/**
 * Created by Freeman on 2016/6/27.
 */
"use strict";

var mongoose = require('../../models/mongoosedb').mongoose,
    User = require('../../models/user.model')/*,
    ccap = require('ccap')()*/;

exports.getCaptcha = function (req,res) {
    /*var ary = ccap.get();
    var txt = ary[0];
    var buf = ary[1];
    req.session.captcha = txt;
    return res.status(200).send(buf);*/
}
/**
 * TODO 待验证
 * */
exports.getMe = function (req,res) {
    var userId = req.user._id;
    User.findByIdAsync(userId).then(function (user) {
        return res.status(200).json(user.userInfo);
    }).catch(function (err) {
        return res.status(401).send();
    });
}


exports.addUser = function (req,res) {

    var nickname = req.body.nickname?req.body.nickname.replace(/(^\s+)|(\s+$)/g,""):'';
    var email = req.body.email?req.body.email.replace(/(^\s+)|(\s+$)/g, ""):'';
    var NICKNAME_REGEXP = /^[(\u4e00-\u9fa5)0-9a-zA-Z\_\s@]+$/;
    var EMAIL_REGEXP = /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/;

    var error_msg;
    if(nickname === ''){
        error_msg = "呢称不能为空";
    }else if(email === '') {
        error_msg = "邮箱地址不能为空";
    }else if(nickname.length <= 2 || nickname.length >15 || !NICKNAME_REGEXP.test(nickname)){
        //不符合呢称规定.
        error_msg = "呢称不合法";
    }else if(email.length <=4 || email.length > 30 || !EMAIL_REGEXP.test(email)){
        error_msg = "邮箱地址不合法";
    }
    if(error_msg){
        return res.status(422).send({error_msg:error_msg});
    }
    var newUser = new User(req.body);
    newUser.role = 'user';
    newUser.saveAsync().then(function (user) {
        return res.status(200).json({success:true,user_id:user._id});
    }).catch(function (err) {
        if(err.errors && err.errors.nickname){
            err = {error_msg:err.errors.nickname.message}
        }
        return res.status(500).send(err);
    });
}

exports.mdUser = function (req,res,next) {
    var nickname = req.body.nickname?req.body.nickname.replace(/(^\s+)|(\s+$)/g, ""):'';
    var NICKNAME_REGEXP = /^[(\u4e00-\u9fa5)0-9a-zA-Z\_\s@]+$/;
    //var EMAIL_REGEXP = /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/;
    //检测一下
    var error_msg;
    if(nickname === ''){
        error_msg = '呢称不能为空';
    }else if(nickname.length <= 2 || nickname.length >15 || !NICKNAME_REGEXP.test(nickname)){
        //不符合呢称规定.
        error_msg = '呢称不合法';
    }
    if(error_msg){
        return res.status(422).send({error_msg:error_msg});
    }

    var user = req.user;
    user.nickname = nickname;
    user.saveAsync().then(function (result) {
        return res.status(200).json({success:true,data:result.userInfo});
    }).catch(function (err) {
        if(err.errors.nickname){
            err = {error_msg:err.errors.nickname.message}
        }
        return res.status(500).send(err);
    });
}